<template>
    <div class="cart-online">
        <div v-if="!isEmpty" class="un-empty">
            <div class="main">
                <div class="in-stock">
                    <!--<div class="in-stock"  v-if="getCartList.iscan && getCartList.nocan.length > 0">-->
                    <div class="single" v-for="(item, index) in cartList.iscan" :key="index">
                        <!--<div class="single" v-for="(item, index) in cartList.nocan" :key="index">-->
                        <svg class="icon selected" aria-hidden="true" :class="goodState.indexOf(item.id) >= 0 ? 'choose' : 'no-choose'" @click="chooseOne(item)">
                            <use xlink:href="#icon-selected"></use>
                        </svg>
                        <img :src="item.pic" />
                        <div class="single-body">
                            <div @click="toDetail(item)">
                                <div class="top">
                                    <span v-if="item.activeTitle">{{ item.activeTitle }}</span>
                                    {{ item.name }}
                                </div>
                                <div class="des">{{ item.title }}</div>
                                <div class="t-r">
                                    <span>{{ item.price | moneyFmt(2, '￥') }}</span>
                                </div>
                            </div>
                            <div class="control">
                                <cart-num-control :min="Number(item.min)" :num="Number(item.num)" isTuangou="item.tuangou" :isCart="true" :goods="item" @changeNum="changeNum" />
                            </div>
                        </div>
                    </div>
                </div>
                <div class="nocan" v-if="cartList.nocan && cartList.nocan.length > 0">
                    <div class="line-title">
                        <div class="border"></div>
                        <span class="line-text">失效商品</span>
                        <div class="border"></div>
                    </div>
                    <div class="single" v-for="(item, key) in cartList.nocan" :key="key">
                        <!-- @click="toInvalid"-->
                        <div class="nocan-close">
                            <svg class="close" aria-hidden="true" @click="delInvalid(item)">
                                <use xlink:href="#icon-close"></use>
                            </svg>
                        </div>
                        <div class="nocan-logo">失效</div>
                        <img :src="item.pic" />
                        <div class="single-body">
                            <div class="notop">{{ item.name }}</div>
                            <div class="des">{{ item.title }}</div>
                            <div class="prc-msg">
                                <div class="not-r">
                                    <span>{{ item.price | moneyFmt(2, '￥') }}</span>
                                </div>
                                <div class="no-control">
                                    {{ item.msg }}
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="newest">
                <div class="line-title">
                    <div class="border"></div>
                    <span class="line-text">最新产品</span>
                    <div class="border"></div>
                </div>
                <div class="newest-goods">
                    <list-goods :goods-list="newestList" @toDetail="toDetail" @add="toAddCart" />
                </div>
                <product-spec :pro-content="specGood" operation="add" ref="fspec" @chooseDone="specChooseOk" v-if="specGood.key" />
            </div>

            <div class="bottom">
                <svg class="selected" aria-hidden="true" :class="allState ? 'choose' : 'no-choose'" @click="chooseAll">
                    <use xlink:href="#icon-selected"></use>
                </svg>
                <div class="all">全选</div>
                <div class="del" @click="delSelected">删除</div>
                <div class="total">
                    合计：
                    <span>{{ totalPrice | moneyFmt(2, '') }}</span>
                    共{{ totalNum }}件
                </div>
                <div class="submit" @click="toOrder">去结算</div>
            </div>
            <confirm ref="confirm" :text="confirmText" confirmText="确定" @confirm="clearTrue" />
        </div>
        <div class="cart-empty" :style="style" v-else>
            <div class="empty" v-if="systemId != 3">
                <img class="empty-img" :src="empty_img | imageFmt" />
                <div class="tip">购物车还是空的哦！</div>
                <div class="tips">快去逛逛吧~</div>
            </div>
            <div class="empty-baby" v-else>
                <img class="empty-img" :src="empty_baby | imageFmt" />
                <div class="tip">购物车还是空的哦！</div>
                <div class="tips">快去逛逛吧~</div>
            </div>
        </div>
    </div>
</template>

<script>
import API from '../../request/api';
import NumControl from '../../components/common/num-control';
import Confirm from '../../components/common/confirm';
import { Toast } from 'vant';
import { commonMixin } from '@/common/mixin';
import CartNumControl from '../../components/Online/cart-num-control';
import ListGoods from '../../components/Online/list-goods';
import ProductSpec from '../../components/Online/product-spec';
import { mapActions } from 'vuex';

const HEIGHT = document.documentElement.clientHeight - 56 + 'px';

export default {
    components: {
        ProductSpec,
        ListGoods,
        CartNumControl,
        Confirm,
        NumControl
    },
    mixins: [commonMixin],
    name: 'cart',
    data() {
        return {
            // isEmpty: true, // 购物车是否为空
            style: {
                height: HEIGHT
            },
            line_width: 45, //tab下划线宽度
            empty_img: 'cart-empty',
            empty_baby: 'cart-empty-baby',
            active: 0, // 购物车类型初始下标
            cartList: {}, // 用于显示的购物车列表
            // temporaryObj: {}, // 购物车列表中转数据
            choosedId: [], // 被选中商品id
            choosedArray: [], // 被选中的商品数据（gid, buyid, num）
            isDelnocan: false, // 是否失效
            allState: false, // 是否全选
            total: 0, // 商品总计价格
            delSuccess: 0, //成功删除商品数量
            system: this.$store.state.login.system,
            newestList: [], // 推荐商品列表
            specGood: {}
        };
    },
    computed: {
        // 是否注册
        isLogin() {
            let userInfo = this.$store.state.login.userInfo;
            let login = userInfo.role === undefined ? false : true;
            console.log('loginlogin:', userInfo, login);
            return login;
        },
        systemId() {
            let system = this.$store.state.login.system;
            system = String(system).substring(0, 1);
            return system;
        },
        // 购物车是否为空
        isEmpty() {
            let empty = true;
            if (JSON.stringify(this.cartList) !== '{}') {
                empty = false;
            }
            // console.log('isEmpty:', empty, this.temporaryObj)
            return empty;
        },
        goodState() {
            // 商品是否选中状态
            if (this.choosedId.length === this.cartList.iscan.length) {
                this.allState = true;
            } else {
                this.allState = false;
            }
            return this.choosedId;
        },
        totalPrice() {
            //商品总计价格 -- 实时
            let price = Number(this.total);
            let list = this.cartList.iscan;
            for (let i in this.choosedId) {
                for (let k in list) {
                    if (this.choosedId[i] === list[k].id) {
                        price = price + Number(list[k].price) * Number(list[k].num);
                    }
                }
            }
            // console.log('price', price, this.choosed.length)
            return price;
        },
        totalNum() {
            //商品总计数量 -- 实时
            let num = 0;
            let list = this.cartList.iscan;
            for (let i in this.choosedId) {
                for (let k in list) {
                    if (this.choosedId[i] === list[k].id) {
                        num = num + Number(list[k].num);
                    }
                }
            }
            return num;
        },
        confirmText() {
            // 弹出框显示内容
            let text = '确定删除所选商品';
            // if(this.isDelnocan) {
            //     text = '确定清空所有失效商品？'
            // } else {
            //     text = '确定删除所选商品？'
            // }
            return text;
        }
        // cartLists(){
        //     return this.cartList
        // }
    },
    methods: {
        ...mapActions(['addToCart']),
        // 获取购物车列表
        getCartList() {
            if (this.isLogin) {
                // 获取购物车列表--已注册
                this.request
                    .get(API.onlineGetCartList)
                    .then(res => {
                        if (res.list.length === 0) {
                            this.cartList = {};
                        } else {
                            this.cartList = res.list;
                            this.chooseAll();
                        }
                        this.hideGlobaLoading(); //关闭loading
                    })
                    .catch(err => {
                        this.hideGlobaLoading(); //关闭loading
                        console.error('onlineGetCartList-err', err);
                    });
            } else {
                if (this.$store.state.online.cart.cartList) {
                    // 获取购物车列表--未注册
                    this.request
                        .post(API.onlineGetCartListPull, {
                            cartList: this.$store.state.online.cart.cartList
                        })
                        .then(res => {
                            if (res.list.length !== 0) {
                                this.cartList = res.list;
                                this.chooseAll();
                            } else {
                                this.cartList = {};
                            }
                            this.hideGlobaLoading(); //关闭loading
                        })
                        .catch(err => {
                            console.error('cart-onlineGetCartListPull-err', err);
                            this.hideGlobaLoading(); //关闭loading
                        });
                } else {
                    this.cartList = {};
                    this.hideGlobaLoading(); //关闭loading
                }
            }
        },
        // 获取推荐商品列表
        getNewestList() {
            // 获取购物车列表--已注册
            this.request
                .get(API.sellwell, {
                    // page: 0,
                    size: 6
                })
                .then(res => {
                    this.newestList.push(...res);
                })
                .catch(err => {
                    this.hideGlobaLoading(); //关闭loading
                    console.error('onlineGetNewestList-err', err);
                });
        },
        // 单独选择
        chooseOne(item) {
            // this.choosedId 为选择的数组，判断当前选择的商品id是否存在于数组之中，若无--添加，若有--删除
            let hasIndex = this.choosedId.indexOf(item.id);
            if (hasIndex < 0) {
                this.choosedId.push(item.id);
                let list = {};
                list.buyid = item.buyid;
                list.gid = item.gid;
                list.num = item.num;
                this.choosedArray.push(list);
            } else {
                this.choosedId.splice(hasIndex, 1);
                this.choosedArray.splice(hasIndex, 1);
            }
        },
        // 更改商品数量
        changeNum(data) {
            if (this.isLogin) {
                this.request
                    .post(API.onlineEditCartGoods, {
                        id: data.id,
                        num: data.num
                    })
                    .then(res => {
                        console.log('onlineEditCartGoods', res);
                    })
                    .catch(err => {
                        console.error('cart-onlineEditCartGoods-err', err);
                    });
            } else {
                let cart = this.$store.state.online.cart;
                cart.cartList[this.system][data.gid][data.buyid].num = data.num;
                this.$store.commit('addToCart_online', cart);
                console.log('changeNum', cart, this.$store.state.online.cart.cartList);
            }
            let hasIndex = this.choosedId.indexOf(data.id);
            if (hasIndex >= 0) {
                this.choosedArray[hasIndex].num = data.num;
            }
        },
        // 全部选择
        chooseAll() {
            // this.allState 是全部选择状态，true为当前是全选
            if (this.allState) {
                // 当前全选-->将选择数组置空
                this.choosedId = [];
                this.choosedArray = [];
            } else {
                // 当前不是全选--> 先将选择数组置空,遍历商品数据，将商品id放入选择数组中
                this.choosedId = [];
                this.choosedArray = [];
                for (let key in this.cartList.iscan) {
                    let list = {};
                    this.choosedId.push(this.cartList.iscan[key].id);
                    list.buyid = this.cartList.iscan[key].buyid;
                    list.gid = this.cartList.iscan[key].gid;
                    list.num = this.cartList.iscan[key].num;
                    this.choosedArray.push(list);
                }
            }
        },
        // 删除选中数据 isDelnocan --> 是否是失效商品
        delSelected() {
            this.isDelnocan = false;
            if (this.choosedId.length > 0) {
                this.$refs.confirm.show(); // 弹出确认弹框
            } else {
                Toast('还没有任何商品被选中哦');
            }
        },
        // 删除失效商品
        delInvalid(item) {
            this.isDelnocan = true;
            let choose = {
                gid: item.gid,
                buyid: item.buyid,
                num: item.num
            };
            this.choosedId.push(item.id);
            this.choosedArray.push(choose);
            this.$refs.confirm.show();
        },
        // 确认删除（清空）
        clearTrue() {
            this.showGlobaLoading(); //打开loading
            if (this.isLogin) {
                this.delMoreCartGoods();
            } else {
                this.delOnlineCartGoods();
            }
        },
        // 登录后删除
        delMoreCartGoods() {
            this.request
                .post(API.onlineDelMoreGoods, {
                    ids: this.choosedId
                })
                .then(res => {
                    this.getCartList();
                    Toast('删除成功');
                })
                .catch(err => {
                    this.hideGlobaLoading(); //关闭loading
                    console.error('delMoreCartGoods-login-err', err);
                });
        },
        // 未登录删除商品
        delOnlineCartGoods() {
            this.delSuccess = 0;
            let cart = this.$store.state.online.cart;
            let array = this.choosedArray;
            if (this.choosedId.length == this.cartList.iscan.length) {
                delete cart.cartList[this.system];
            } else {
                for (let k in array) {
                    delete cart.cartList[this.system][array[k].gid][array[k].buyid];
                    if (JSON.stringify(cart.cartList[this.system][array[k].gid]) === '{}') {
                        delete cart.cartList[this.system][array[k].gid];
                    }
                    if (JSON.stringify(cart.cartList[this.system]) === '{}') {
                        delete cart.cartList[this.system];
                    }
                    if (cart.cartNum[this.system].cartNum !== 0) {
                        cart.cartNum[this.system].cartNum--;
                    }
                }
            }
            this.$store.commit('addToCart_online', cart);
            this.getCartList();
            Toast('删除成功');
        },
        // 去创建订单
        toOrder() {
            if (this.choosedId.length > 0) {
                let orderData = {
                    data: this.choosedArray,
                    is_cart: true
                };
                this.$store.commit('dataCreateOrder', orderData);
                // 加是否注册判断
                if (this.isLogin) {
                    this.$router.push({
                        name: 'order-created'
                    });
                } else {
                    this.$router.push({
                        name: 'login',
                        query: {
                            direct: 'order-created'
                        }
                    });
                }
            } else {
                Toast('还没有任何商品被选中哦');
            }
        },
        // 去商品详情
        toDetail(good) {
            this.$router.push({
                name: 'online-detail',
                query: {
                    gid: good.gid,
                    type: this.system
                }
            });
        },
        toAddCart(good) {
            let that = this;
            this.specGood = {};
            if (good.status == 3) {
                this.request
                    .get(API.frontGetMiniGood, {
                        gid: good.gid
                    })
                    .then(res => {
                        console.log('frontGetMiniGood', res);
                        this.goodId = good.gid;
                        this.specGood = res;
                        this.specGood.pic = good.pic;
                        setTimeout(() => {
                            that.$refs.fspec.show();
                        }, 5);
                    })
                    .catch(err => {
                        console.error('frontGetMiniGood-err', err);
                    });
            } else {
                this.$toast('该商品暂不可操作');
            }
        },
        specChooseOk(sku) {
            sku.system = this.$store.state.login.system;
            sku.gid = this.goodId;
            if (sku.buyid) {
                if (this.isLogin) {
                    // 购物车添加商品（已注册）
                    this.request
                        .post(API.onlineAddCartGoods, {
                            gid: sku.gid,
                            buyid: sku.buyid,
                            num: sku.count
                        })
                        .then(res => {
                            console.log('onlineAddCartGoods', res);
                        })
                        .catch(err => {
                            console.error('onlineAddCartGoods-err', err);
                        });
                } else {
                    this.addToCart(sku);
                }
                this.$toast('加入购物车成功');
                setTimeout(() => {
                    location.reload();
                }, 500);
                // this.getCartList();
            }
        }
    },
    watch: {
        cartList: {
            handler(newVal, oldVal) {
                // ...
            },
            deep: true,
            immediate: true
        }
    },
    created() {
        // 外层动画关闭
        // document.getElementById('img').style.display = 'none';
        this.showGlobaLoading(); //打开loading
        this.getCartList();
        this.getNewestList();
    },
    mounted() {}
};
</script>

<style lang="stylus" rel="stylesheet/stylus" scoped>
@import '~@/assets/main.styl'
.cart-online {
    background-color #f5f5f5
}

.new-list {
    position fixed
    z-index 99
    margin-top 0
}

>>> .van-tabs--line .van-tabs__wrap {
    height vw(45)
    font-size vw(14)
}

>>> .van-tab {
    font-size vw(14)
}

.cart-empty {
    height 100%
    background-color grayF

    .empty {
        display flex
        flex-direction column
        align-items center
        width vw(375)
        height 100%
        overflow-y hidden

        img {
            width vw(81)
            height vw(146)
            margin-top 45%
        }

        .tip {
            font-size vw(16)
            color gray3
            line-height vw(21)
            margin-top vw(55)
        }

        .tips {
            word-vw(word14, gray9)
            line-height vw(19)
            margin-top titleMargin
        }
    }

    .empty-baby {
        display flex
        flex-direction column
        align-items center
        width vw(375)
        height 100%
        overflow-y hidden
        background-color grayF

        img {
            /*border #5A124A 1px solid*/
            width vw(176)
            height vw(178)
            margin-top 40%
        }

        .tip {
            font-size vw(16)
            color gray3
            line-height vw(21)
            //margin-top vw(51)
        }

        .tips {
            word-vw(word14, gray9)
            line-height vw(19)
            margin-top titleMargin
        }
    }

}

.un-empty {
    margin-bottom vw(130)

    img {
        width vw(80)
        height vw(80)
        margin-left vw(50)
    }

    .selected {
        position absolute
        left smallMargin
        width vw(20)
        height vw(20)
    }

    .no-choose {
        fill grayE
    }

    .choose {
        fill main-color
    }

    .main {
        //position absolute
        //margin-top vw(55)
        //margin-bottom vw(200)

        .single {
            background grayF
            width vw(375)
            height vw(130)
            display flex
            position relative
            align-items center
            border-top 1px solid #f8f8f8
            margin-top smallMargin
        }

        .single-body {
            position relative
            height vw(80)
            flex 1
            /*border indianred solid 1px*/
        }

        .top {
            margin-left smallMargin
            word-vw(word14, gray3)
            /*width 65%*/
            width: 90% !important;
            multi(2);
            height vw(19)
            line-height vw(19)

            span {
                width vw(40)
                height vw(20)
                padding vw(0) vw(8) vw(0) vw(8)
                background-color #f8f8f8
                border 1px solid main-color
                border-radius vw(30)
                box-sizing border-box
                text-align center
                line-height vw(16)
                word-vw(word12, main-color)
            }
        }

        .des {
            margin-left smallMargin
            word-vw(word12, gray9)
            position absolute
            margin-top titleMargin
            width: 90% !important;
            multi(2);
            height vw(24)
        }

        .t-r {
            margin-left smallMargin
            word-vw(word14, gray3)
            position absolute
            height vw(19)
            line-height vw(19)
            bottom 0 /*span{
                color main-color
            }*/
        }

        .control {
            position absolute
            display flex
            flex-wrap nowrap
            word-vw(word12, gray9)
            line-height vw(16)
            height vw(22)
            right smallMargin
            bottom 0
        }
    }

    .nocan {
        margin-top middleMargin

        img {
            margin-left vw(20)
        }

        .nocan-close {
            width vw(18)
            height vw(19)
            background-color grayE
            border-bottom-left-radius all-radius
            position absolute
            right 0
            top 0

            .close {
                width vw(9)
                height vw(9)
                fill grayF
                margin-left vw(5)
            }
        }

        .notop {
            margin-left smallMargin
            word-vw(word14, gray9)
            /*width 65%*/
            width: 90% !important;
            multi(2);
            height vw(19)
            line-height vw(19)

            span {
                width vw(40)
                height vw(20)
                padding vw(0) vw(8) vw(0) vw(8)
                background-color #f8f8f8
                border 1px solid main-color
                border-radius vw(30)
                box-sizing border-box
                text-align center
                line-height vw(16)
                word-vw(word12, main-color)
            }
        }

        .prc-msg {
            display flex
            justify-content space-between
            margin-top middleMargin

            .not-r {
                margin-left smallMargin
                word-vw(word14, gray9)
                position absolute
                height vw(19)
                line-height vw(19)
                margin-top middleMargin
            }

            .no-control {
                position absolute
                display flex
                flex-wrap nowrap
                word-vw(word12, gray9)
                line-height vw(16)
                width vw(85)
                height vw(22)
                right smallMargin
                bottom 0
            }
        }

    }

    .nocan-logo {
        width vw(30)
        height vw(20)
        border-radius all-radius
        background-color #f2f2f2
        margin-left titleMargin
        word-vw(word12, gray9)
        display flex
        justify-content center
        align-items center
        text-align center
    }

    .line-title {
        width vw(375)
        height vw(45)
        display flex
        align-items center
        justify-content center
        text-align center

        .line-text {
            margin 0 middleMargin
            word-vw(word16, gray9)
        }

        .border {
            width vw(91)
            border 1px solid gray9
        }
    }

    .newest {
        margin-top smallMargin
        width 100%
        display flex
        flex-direction column
        /*.newest-goods{*/
        /*margin-top smallMargin*/
        //}
    }

    .bottom {
        background grayF
        position fixed
        bottom vw(55)
        width 100%
        height vw(60)
        line-height vw(21)
        display flex
        align-items center
        /*box-sizing border-box*/
        word-vw(word16, gray3)

        .all {
            position absolute
            left vw(50)
        }

        .del {
            position absolute
            left vw(100)
        }

        .total {
            position absolute
            display flex
            flex-wrap wrap
            width 30%
            right vw(115)

            span {
                color main-color
            }
        }

        .submit {
            small-solid()
            font-size word16
            position absolute
            right middleMargin
            display flex
            align-items center
            text-align center
            justify-content center
        }
    }
}
</style>
